/*************************************************************************************
 * mappoints.js
 * -----------
 * phpGMapTrips 
 * 
 * This php application allows you to easily record your travel destinations 
 * and display them with Google maps.
 * 
 * Author: Stephane Coste (lescoste@gmail.com)
 * Copyright: (c) 2006 Stephane Coste (http://lescoste.net/)
 * Release Version: 0.1
 * CVS Revision Version: $Revision: 1.4 $
 * Date Started: 2006/02/19
 * Last Modified: $Date: 2007/03/17 08:41:59 $
 *
 *************************************************************************************
 *
 *     This file is part of phpGMapTrips.
 *
 *   phpGMapTrips is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   phpGMapTrips is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with phpGMapTrips; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 ************************************************************************************/
// -------------------------------------------
// phpGMapTrips javascript functions
// -------------------------------------------
var mapProvider = "google";
var map; // google map object
var mapzoom; // google map zoom object 
var mapyahoo; // yahoo map zoom object 
var geocoder;
var currentZoomLevel=5;
var bounds; // all points on map

var currentOverlay; // clicked red point overlay on map 
var selectOverlay; // green point overlay on map 
var selectOverlayZoom; // green point overlay on mapzoom 
var selectOverlayYZoom; // green point overlay on yahoo mapzoom 
var movedOverlay; // new point overlay in map
var movedOverlayZoom; // new point overlay in mapzoom
var markerArray; // all trip map markers
var markerZoomArray; // all trip mapzoom markers

var myMapPolyline; // google map polyline
var myMapzoomPolyline; // google map polyline

// Create our "tiny" default marker icon
var redIcon = new GIcon();
redIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
redIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
redIcon.iconSize = new GSize(12, 20);
redIcon.shadowSize = new GSize(22, 20);
redIcon.iconAnchor = new GPoint(6, 20);
redIcon.infoWindowAnchor = new GPoint(5, 1);

// create the current point marker icon
var greenIcon = new GIcon(redIcon);
greenIcon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";

// create the new point marker icon
var yellowIcon = new GIcon(redIcon);
yellowIcon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";

var windowWidth = 0, windowHeight = 0;
function displayInitialMapDivs() {
var agt=navigator.userAgent.toLowerCase();
         if(agt.indexOf('msie')!=-1){
		if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		updateMapDivs("mapcontainer", 150, 150, 100);
		//updateMapDivs("map", 143, 143, 110);
		var wh = windowHeight - 5;
		var ww = windowWidth - 5;
		updateMapDivs("mapzoom", ww, wh, 10);
	}
}
function displayInitialGadgetMapDivs() {
var agt=navigator.userAgent.toLowerCase();
         if(agt.indexOf('msie')!=-1){
		if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		var wh = windowHeight - 5;
		var ww = windowWidth - 5;
		updateMapDivs("mapzoom", ww, wh, 10);
	}
}

function updateMapDivs(map, w, h, z) {
        var mapdiv = document.getElementById(map);
	mapdiv.style.width = ""+w+"px";
	mapdiv.style.height = ""+h+"px";
	mapdiv.style.zIndex = ""+z;
}

function checkZoomLevel(map) {
// zoom out to a level that has images
G_HYBRID_MAP.getErrorMessage = function() {
	var z = map.getZoom(); 
	//if (z > 0 && !tilesPending) { 
	if (z > 8) { 
		map.setZoom(z - 1); 
		return ""; 
	} 
	return "No data available at this zoom level."; 
}
}

function showGoogleMap() {
	if(mapProvider != "google") {
                toggleMapProvider("google");
		showMapzoom(10);
		selectPointNameMap(currentAPoint);
	}
}
function toggleMapProvider(provider) {
        var oldmap = "mapzoom";
      // hide current provider
        if (mapProvider == "yahoo") {
            oldmap = "mapyahoo";
        }
        var mapdiv = document.getElementById(oldmap);
        mapdiv.style.zIndex = "0";

     // show new one
        var newmap = "mapzoom";
        if (provider == "yahoo") {
            newmap = "mapyahoo";
        }
        mapdiv = document.getElementById(newmap);
        mapdiv.style.zIndex = "10";

	mapProvider = provider;
}

// display the current trip map
function showMap(zoomlevel) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(default_lat, default_lng), zoomlevel);
		setMapType(map, default_map_mapType);
}
function setMapType(amap, type) {
	if (type == "HYBRID_MAP") {
		amap.setMapType(G_HYBRID_MAP); 
	} else if (type == "SATELLITE_MAP") {
		amap.setMapType(G_SATELLITE_MAP); 
	} else {
		amap.setMapType(G_NORMAL_MAP); 
	}
}

// display the current point map
function showMapzoom(zoomlevel) {
        mapzoom = new GMap2(document.getElementById("mapzoom"));
        //mapzoom.setCenter(new GLatLng(48.77832281861946, 2.315164804458618), zoomlevel);
        mapzoom.setCenter(new GLatLng(default_lat, default_lng), zoomlevel);
	mapzoom.addControl(new GLargeMapControl());
	mapzoom.addControl(new GMapTypeControl());
	setMapType(mapzoom, default_mapzoom_mapType);

        //  ======== Add a map overview ==========
          mapzoom.addControl(new GOverviewMapControl(new GSize(150,150)));
        //  ======== Cause the overview to be positioned AFTER IE sets its initial position ======== 
	  setTimeout("positionOverview(558,254)",100);

        geocoder = new GClientGeocoder();

}
// display the current point map
function showMapGadget(zoomlevel) {
        mapzoom = new GMap2(document.getElementById("mapzoom"));
        mapzoom.setCenter(new GLatLng(48.77832281861946, 2.315164804458618), zoomlevel);
	mapzoom.addControl(new GSmallZoomControl());
	mapzoom.addControl(new GMapTypeControl());
        setMapType(mapzoom, default_mapgadget_mapType);

        geocoder = new GClientGeocoder();
}
//  ======== A function to adjust the positioning of the overview ========
function positionOverview(x,y) {
	var omap=document.getElementById("map_overview");
	if (omap != undefined) {
	omap.style.left = x+"px";
	omap.style.top = y+"px";

	// == restyling ==
	omap.firstChild.style.border = "1px solid gray";

	omap.firstChild.firstChild.style.left="4px";
	omap.firstChild.firstChild.style.top="4px";
	omap.firstChild.firstChild.style.width="190px";
	omap.firstChild.firstChild.style.height="190px";

	setMapType(omap, default_omap_mapType);
	}
}


function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      mapzoom.setCenter(point, 13);
      var marker = new GMarker(point);
      mapzoom.addOverlay(marker);
      marker.openInfoWindowHtml(address);
    }
  );
}


// zoom in to that coordinates
function zoomIn(lat, lng) {
	mapzoom.setCenter(new GLatLng(lat, lng), 13);
}

function setCurrentPoint(overlay) {
	currentOverlay = overlay;
}
// Creates a marker(overlay) whose info window displays the given text 
function createMarker(mapname, point, name, ptitle, ptext, icon, mapProv) {
	if(mapProv == "yahoo") {
		// Create a marker positioned at a lat/lon
		var marker = new YMarker(point);
		// Add a label to the marker
		marker.addLabel(ptitle);
		// Add auto expand
		marker.addAutoExpand("<div>"+ptext+"</div>");
		// Call onSmartWinEvent when the user clicks on the marker
		//YEvent.Capture(marker, EventsList.MouseClick, onSmartWinEvent);
		return marker;
	} else {
		var marker = new GMarker(point, {title:ptitle, icon:icon, draggable:true});
                if (mapname == "mapzoom") {
		   // Show this marker index in the info window when it is clicked
		   GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(ptext);
				if (StateManager != undefined){
				// remember back url
				var pageid = getPageId(currentFile, currentTrip, name);
				var pagetitle = getPageTitle(currentFile, currentTrip, name);
				StateManager.setState(pageid, pagetitle);
				}
				});
		   GEvent.addListener(marker, "dragstart", function() {
				   mapzoom.closeInfoWindow();
				   });

		   GEvent.addListener(marker, "dragend", function() {
				marker.openInfoWindowHtml(ptext);
				editCurrentPoint(name, marker);
				   });
                }
		return marker;
	}
}

// display current point details in editZone 
function showPointDetails(point) {
	if (point == undefined) {
		if (tripPoints == undefined) {
			return;
		} else {
			point = tripPoints[currentAPoint];
		} 
	}
	editMode =false;
	//var pname = document.getElementById("p_name");
	//pname.innerHTML = getPointDetails(point);

	//toggleEditPoint();
}

function selectPointNameMap(name, zoomin) {
	if (tripPoints == undefined) {
		return;
	}
	var point = tripPoints[name];

        if (point == undefined) {
            return;
        }
        
	// show point on map
	selectPoint(name);

	// show point on mapzoom
	if(mapProvider == "yahoo") {
		var ypoint = new YGeoPoint(parseFloat(point.getAttribute("lat")), parseFloat(point.getAttribute("lng")));
		mapyahoo.drawZoomAndCenter(ypoint, currentZoomLevel);
		selectOverlayYZoom = createMarker("mapzoom", ypoint, name, point.getAttribute("title"), getPointDetails(point), greenIcon, mapProvider);
	        mapyahoo.addOverlay(selectOverlayYZoom);
	} else {
		markerZoomArray[name].setImage(greenIcon.image);
		selectOverlayZoom = markerZoomArray[name];
		// Show this marker index in the info window when it is clicked
  		selectOverlayZoom.openInfoWindowHtml(getPointDetails(point));
//                mapzoom.panTo(selectOverlayZoom.getPoint());
	}

	// show point on map
        if (zoomin) {
	   zoomIn(point.getAttribute("lat"), point.getAttribute("lng"));
        }
}

// show green point on map
function selectPoint(name) {
	if(map != undefined && markerArray[name] != undefined) {
		markerArray[name].setImage(greenIcon.image);
		selectOverlay = markerArray[name];
	}
}

function removeSelectPoint() {
       if (selectOverlay != undefined) {
               selectOverlay.setImage(redIcon.image);
       }
}
function unShowPointMapZoom() {
       // unshow point on mapzoom
       //mapzoom.clearOverlays();
         if (selectOverlayZoom != undefined) {
               selectOverlayZoom.setImage(redIcon.image);
       }
}

/*
 displays a new point on the map and mapzoom
 and if in edit mode, update the current point lat/long
 called when a new click is done on map or mapzoom
*/
function addPoint(point) {
        var addPointName = "New Place";
	if(map != undefined){
		if (movedOverlay != undefined) {
			map.removeOverlay(movedOverlay);
		}
		movedOverlay = createMarker("map", point, addPointName, addPointName, addPointName, yellowIcon, "google");
		movedOverlay.my_name = addPointName;
		map.addOverlay(movedOverlay);
	}
	if (movedOverlayZoom != undefined) {
		mapzoom.removeOverlay(movedOverlayZoom);
	}
	movedOverlayZoom = createMarker("mapzoom", point, addPointName, addPointName, getAddPointDetails(point), yellowIcon, mapProvider);
	movedOverlayZoom.my_name = addPointName;
	mapzoom.addOverlay(movedOverlayZoom);
	if (editMode) {
		// move point
		var f = window.editpointiframename;
                if (f != undefined) {
		   f.document.formeditpoints.editLat.value = point.y;
		   f.document.formeditpoints.editLng.value = point.x;
                }
	}
}


// draw trip points and line
function drawTrip(name, pointname) {
	points = [];
	markerArray = [];
	markerZoomArray = [];
	var tripdata = trips[name];
	var markers = tripdata.getElementsByTagName("marker");
	var orderedPoints = tripdata.getElementsByTagName("point");
	var tripGroups = tripdata.getElementsByTagName("groups");
	var groupTrips = tripdata.getElementsByTagName("grouptrip");
	if(map != undefined) {
		map.clearOverlays();
	}
	mapzoom.clearOverlays();
	bounds = new GLatLngBounds();

	// create arrays for ordered points
	tripOrderedPoints = new Array();
	tripOrderedPointsName = new Array();
	for (var j = 0; j < orderedPoints.length; j++) {
		tripOrderedPoints[orderedPoints[j].getAttribute("seq")] = orderedPoints[j];
		tripOrderedPointsName[orderedPoints[j].getAttribute("name")] = orderedPoints[j];
	}

	// draw markers on map
	tripPoints = new Array();
	for (var j = 0; j < markers.length; j++) {
		var i = j;
		// record hashmap : name => markers
		var place = markers[i].getElementsByTagName("place");
		for (var k = 0; k < place.length; k++) {
			tripPoints[place[k].getAttribute("name")] = markers[i];
		}

		if(map != undefined) {
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
			var marker = createMarker("map", point, markers[i].getAttribute("name"), markers[i].getAttribute("title"), getPointDetails(markers[i]), redIcon, "google");
			marker.my_name = markers[i].getAttribute("name");
			markerArray[marker.my_name] = marker;
			map.addOverlay(marker);
		}
 
                // add point on mapzoom too
		var pointz = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
		var markerz = createMarker("mapzoom", pointz, markers[i].getAttribute("name"), markers[i].getAttribute("title"), getPointDetails(markers[i]), redIcon, mapProvider);
		markerz.my_name = markers[i].getAttribute("name");
		markerZoomArray[markerz.my_name] = markerz;
		mapzoom.addOverlay(markerz);

		// if no order specified, draw line per alphabetical order
		if (tripOrderedPoints.length == 0) {
			// store points for line tracing
			points.push(point);
			// store point for center and zoom  
			bounds.extend(point);
		}
        }
	// draw polyline
	if (tripOrderedPoints.length > 0) {
		for (var j = 0; j < tripOrderedPoints.length; j++) {
			var lat = "";
			var lng = "";
			if(tripOrderedPoints[j] == undefined) {
					continue;
			}
			if(tripOrderedPoints[j].getAttribute("lat") == undefined){
				// get lat/lng from existing point
				var mymarker = tripPoints[tripOrderedPoints[j].getAttribute("name")];
				if(mymarker == undefined){
					continue;
				}
				lat = mymarker.getAttribute("lat");
				lng = mymarker.getAttribute("lng");
			} else {
				// get lat/lng from ordered point itself
				lat = tripOrderedPoints[j].getAttribute("lat");
				lng = tripOrderedPoints[j].getAttribute("lng");
			}
			var point = new GLatLng(parseFloat(lat), parseFloat(lng));
			// store points for line tracing
			points.push(point);
			// store point for center and zoom  
			bounds.extend(point);
		}
		// add points that are new = not ordered
		for (var j = 0; j < markers.length; j++) {
			var place = markers[j].getElementsByTagName("place");
			for (var k = 0; k < place.length; k++) {
				if (tripOrderedPointsName[place[k].getAttribute("name")] == undefined) {
					var point = new GLatLng(parseFloat(place[k].getAttribute("lat")), parseFloat(place[k].getAttribute("lng")));
					// store points for line tracing
					points.push(point);
					// store point for center and zoom  
					bounds.extend(point);
				}
			}
		}
	}

	// print point list
	var menuelem = document.getElementById("menu_places");
        var menucontent = "";

	menucontent += getPlacesTools((tripsSummary[name] != undefined && tripsSummary[name].getAttribute("g") == "t"));
	menucontent += getMenuSepar();

	// print all points that are ordered
	for (var j = 0; j < tripOrderedPoints.length; j++) {
			if(tripOrderedPoints[j] == undefined) {
					continue;
			}
		if(tripOrderedPoints[j].getAttribute("lat") == undefined){
			menucontent += addPointInList(tripOrderedPoints[j].getAttribute("name"), tripPoints[tripOrderedPoints[j].getAttribute("name")].getAttribute("title"));
		}
	}
	// print points that are not ordered
	for (var j = 0; j < markers.length; j++) {
		var place = markers[j].getElementsByTagName("place");
		for (var k = 0; k < place.length; k++) {
			if(tripOrderedPointsName[place[k].getAttribute("name")] == undefined) {
				menucontent += addPointInList(place[k].getAttribute("name"), place[k].getAttribute("title"));
			}
		}
	}

	// display groups list
	if (tripGroups.length >0) {
		menucontent += addGroupInList(tripGroups[0].getAttribute("name"));
	}
	// display group trips
	for (var j = 0; j < groupTrips.length; j++) {
		menucontent += addGroupInList(groupTrips[j].getAttribute("name"));
	}

        menuelem.innerHTML = menucontent;

	// position and zoom maps
	if(map != undefined) {
		showAllPoints(map, bounds);
	}
	showAllPoints(mapzoom, bounds);

	var color = getRandomColor();
	if(map != undefined) {
		myMapPolyline = new GPolyline(points, color);
	}
	myMapzoomPolyline = new GPolyline(points, color);
	showPolylines();
}
function showAllPoints(amap, bounds) {
	// position and zoom maps
        var estimatedMapzoom = amap.getBoundsZoomLevel(bounds);
        if (estimatedMapzoom > 15) {
           estimatedMapzoom = 4;
        }
        amap.setZoom(estimatedMapzoom);
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	amap.setCenter(new GLatLng(clat,clng));
}

var mappolylinemode = "normal";
function toggleMapPolyline(){
	if (mappolylinemode == "normal") {
		hidePolylines();
		mappolylinemode = "hide";
	} else {
		showPolylines();
		mappolylinemode = "normal";
	}
}
function showPolylines() {
	if(map != undefined) {
		map.addOverlay(myMapPolyline);
	}
	mapzoom.addOverlay(myMapzoomPolyline);
}
function hidePolylines() {
	if(map != undefined) {
		map.removeOverlay(myMapPolyline);
	}
	mapzoom.removeOverlay(myMapzoomPolyline);
}

function addPointInList(name, title) {
	// show point list
	return "<a id='a_"+ name +"' href='javascript:void(0);' class='menuItem triplink' style='color:blue;' onclick='selectPointName(\"" + name + "\");' title='"+lang_trips_show_link+" " + title + "'>"+title + "</a>"+" ";
}
function addGroupInList(name) {
	// show group list
	return "<span class='groupname'>"+name+"</span>"+" ";
}

function exportToKml() {
	window.open("exportkml.php?file="+escape(currentFile)+"&langue="+escape(langue)+"&showtrip="+escape(currentTrip), "exportToKml_"+currentTrip, "width=200,height=200");
}
// trip colors
/*
colorElements = new Array(
		"0000FF", // blue
		"FF0000", // red
		"00FF00", // lime
		"000000"  // black
		);
		*/
function getRandomColor() {
//	c = colorElements[Math.floor(Math.random()*(colorElements.length-1))];
//	return ("#"+c);
	//return ("#00FF00"); // lime
	return ("#FF0000"); // red
}
